package Za

import (
	"fmt"
	"net/http"
	"os"

	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var Logger *zap.Logger
var Sugurlogger *zap.SugaredLogger

func getEncoder() zapcore.Encoder {
	return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
}

func getWriter() zapcore.WriteSyncer {
	file, _ := os.Create(viper.GetString("log.filename"))
	return zapcore.AddSync(file)
}

func InitLogger() {
	writesyncer := getWriter()
	encorder := getEncoder()
	//修改日志等级
	var l = new(zapcore.Level)
	err := l.UnmarshalText([]byte(viper.GetString("log.level")))
	if err != nil {
		return
	}
	var core zapcore.Core
	fmt.Printf("mode value:%s\n", viper.GetString("mode"))
	if viper.GetString("mode") == "dev" {
		//控制台开发模式
		consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
		core = zapcore.NewTee(
			zapcore.NewCore(encorder, writesyncer, l),
			zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel))
	} else {
		core = zapcore.NewCore(encorder, writesyncer, l)
	}

	Logger = zap.New(core, zap.AddCaller())
	// logger, _ = zap.NewProduction()
	Sugurlogger = Logger.Sugar()
}

// 第二步：通过Logger调用Info/Error等输出日志
func simpleHttpGet(url string) {
	resp, err := http.Get(url)
	if err != nil {
		Logger.Error("Error fetching url..",
			zap.String("url", url),
			zap.Error(err))
	} else {
		Logger.Info("Success..",
			zap.String("statusCode", resp.Status),
			zap.String("url", url))
		resp.Body.Close()
	}
}

func Init() {
	InitLogger()
	defer Logger.Sync()
	fmt.Printf("running Log success\n")
}
